package com.jay.media.music.core.audio

import android.content.Context
import android.media.MediaRecorder
import android.os.Build
import android.util.Log

/**
 * @author xuzhou4
 * @date 2022/1/28
 */
class MediaRecordUtils {
    companion object {
        const val TAG = "MediaRecordUtils"
    }

    private var mediaRecorder: MediaRecorder? = null

    fun startRecord(context: Context, outPutPath: String) {
        Log.d(TAG, "startRecord() called with: context = $context, outPutPath = $outPutPath")
        mediaRecorder = createMediaRecorder(context)
        mediaRecorder?.let {
            it.setAudioSource(MediaRecorder.AudioSource.MIC)
            it.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS)
            it.setOutputFile(outPutPath)
            it.setAudioChannels(2)
            it.setAudioSamplingRate(44100)
            it.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
            it.prepare()
            it.start()
        }
    }

    fun stopRecord() {
        mediaRecorder?.let {
            it.stop()
            it.release()
        }
        mediaRecorder = null
    }

    fun createMediaRecorder(context: Context): MediaRecorder {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            MediaRecorder(context)
        } else {
            MediaRecorder()
        }
    }
}